import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:jxchmz/%E4%BB%93%E7%AE%A1/%E7%89%A9%E6%96%99%E7%B1%BB%E5%88%AB%E7%AE%A1%E7%90%86/MaterialTypeManageAdd.dart';
import 'package:jxchmz/%E4%BB%93%E7%AE%A1/%E7%89%A9%E6%96%99%E7%B1%BB%E5%88%AB%E7%AE%A1%E7%90%86/MaterialTypeManageUpdate.dart';
import 'package:jxchmz/API/%E5%BA%93%E5%AD%98%E7%AE%A1%E7%90%86/KuCunManager.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';

class MaterialTypeManageList extends StatefulWidget {
  @override
  _MaterialTypeManageListState createState() => new _MaterialTypeManageListState();
}

class _MaterialTypeManageListState extends State<MaterialTypeManageList> {
  TextEditingController SearchController = new TextEditingController();

//物料类别列表
  List GoodsTypeList = [];

  // 当前页数
  int _page = 1;

  // 是否还有
  bool _hasMore = true;

  // 滚动控制器
  ScrollController _scrollController = new ScrollController();
//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 监听滚动事件
    _scrollController.addListener(() {
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixel = _scrollController.position.pixels;
      if (maxScroll == pixel) {
        if (_hasMore) {
          _page++;
          GetlistGoodsType();
        }
      }
    });

    Future.delayed(Duration.zero, () {
      GetlistGoodsType();
    });
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return  Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: CupertinoSearchTextField(
            controller: SearchController,
            placeholder: "Enterthemembernametosearch".tr,
            placeholderStyle: TextStyle(fontSize: 13, color: Colors.black38),
          ),
          centerTitle: true,
          elevation: 0,
          iconTheme: IconThemeData(
            color: Colors.black
          ),
          actions: [
            TextButton(
                onPressed: () {
                  //搜索事件
                  SearchOrder();
                },
                child: Text(
                  "Search".tr,
                  style: TextStyle(color: Colors.black),
                ))
          ],
        ),
      body: Container(
        child: ListView.separated(
            itemBuilder: (context, index) {
              return ListTile(
                title: Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          child: Text(
                            "MaterialTypeName".tr+":${GoodsTypeList[index]['name']}",
                            style: TextStyle(fontSize: 13),
                          ),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [

                            GestureDetector(
                              child: Row(
                                children: [
                                  Icon(Icons.edit,color: Colors.black26,size: 15,),
                                  Text("revise".tr,style: TextStyle(fontSize: 13,color: Colors.black26),)
                                ],
                              ),
                              onTap: (){
                                //进入详情
                                Get.to(MaterialTypeManageUpdate(),arguments: {"Order":GoodsTypeList[index]})!.then((value){
                                  SearchOrder();
                                });
                              },
                            ),
                            Container(
                              width: 5,
                            ),
                            GestureDetector(
                              child: Row(
                                children: [
                                  Icon(Icons.delete,color: Colors.black26,size: 15,),
                                  Text("Delete".tr,style: TextStyle(fontSize: 13,color: Colors.black26),)
                                ],
                              ),
                              onTap: (){
                                Get.defaultDialog(
                                    title: "prompt".tr,
                                    middleText: "Areyousureyouwanttodeletethismaterialcategory".tr,
                                    barrierDismissible: false,
                                    confirm: MaterialButton(
                                      onPressed: () async {
                                        Get.back();
                                        GoodsTypeDelete(GoodsTypeList[index]['id']);
                                      },
                                      child: Text("sure".tr,style: TextStyle(color: Colors.white),),
                                      color: Color(0xff372D9F),
                                    ),
                                    cancel: MaterialButton(
                                      onPressed: () {
                                        Get.back();
                                      },
                                      child: Text(
                                        "Cancel".tr,
                                        style: TextStyle(color: Color(0xff372D9F)),
                                      ),
                                      color: Colors.white,
                                      //边框样式
                                      shape: const RoundedRectangleBorder(
                                        //边框颜色
                                        side: BorderSide(
                                          color: Color(0xff372D9F),
                                          width: 1,
                                        ),
                                      ),
                                    ));
                              },
                            )

                          ],
                        )
                      ],
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    ),
                    Container(
                      height:10,
                    ),
                    Container(
                      alignment: Alignment.centerLeft,
                      child: Text("MaterialTypestatus".tr+":${GoodsTypeList[index]['isEnabled']==0?"enable".tr:"Notenabled".tr}", style: TextStyle(fontSize: 13, color: GoodsTypeList[index]['isEnabled']==0?Colors.red:Colors.blue)),
                    ),
                    // Row(
                    //   mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    //   children: [
                    //     Container(
                    //       child: Text(
                    //           "remark".tr+":${GoodsTypeList[index]['remark']}",
                    //           style: TextStyle(fontSize: 13)),
                    //     ),
                    //   ],
                    // ),


                  ],
                ),
              );
            },
            separatorBuilder: (context, index) {
              return Divider();
            },
            itemCount: GoodsTypeList.length),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          //添加类别
          Get.to(MaterialTypeManageAdd())!.then((value){
            //刷新物料类别列表
            SearchOrder();
          });
        },
      ),
    );
  }
  //搜索事件
  SearchOrder() {
    _page = 1;
    _hasMore = true;
    GoodsTypeList = [];
    GetlistGoodsType();
  }
  //获取物资类别
  GetlistGoodsType() async {
    //取出本地个人信息
    GetStorage getStorage = new GetStorage();
    var Userid = json.decode(getStorage.read("User"))['user']['userId'];
    //搜索参数
    var data = {"pageNum": _page, "pageSize": 10, "reasonable": false, "name": SearchController.text};
    var ResponseData = await KuCunManager().GetGoodsTypeNoAll(data);
    if (ResponseData['code'] == 200) {
      var List = ResponseData['rows'];
      if (List.length <= 0) {
        // 关闭加载
        this._hasMore = false;
      } else {
        List.forEach((element) {
          GoodsTypeList.add(element);
        });
      }
    } else {
      new GetxTools().ErrorToast("Memberlistacquisitionfailed".tr);
    }
    setState(() {});
  }
  //删除物资类别
  GoodsTypeDelete(id) async {
    //取出本地个人信息
    GetStorage getStorage = new GetStorage();
    KSProgressDialog().LoadingToast("Deleteing".tr, context);
    var ResponseData = await KuCunManager().DeleteGoodsType(id);
    KSProgressDialog().CloseLoading();
    if (ResponseData['code'] == 200) {
      GetxTools().SuccessToast("Thedeletionwassuccessful".tr);
      SearchOrder();
    } else {
      new GetxTools().ErrorToast("Memberdeletionfailed".tr);
    }
    setState(() {});
  }
}
